<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户姓名" prop="customerName">
        <el-input v-model="queryParams.customerName" placeholder="请输入客户姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="联系方式" prop="customerPhone">
        <el-input v-model="queryParams.customerPhone" placeholder="请输入联系方式" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="车牌号码" prop="licensePlate">
        <el-input v-model="queryParams.licensePlate" placeholder="请输入车牌号码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- 
        到时候携带时间字符串参数格式是 yyyy-MM-dd HH:mm:ss 
        若请求数据是 JSON格式的，用注解 @JsonFormat（接收参数和响应数据都用到这个注解）
        若请求数据是 表单格式，二进制格式，用注解 @DatetimeFormat

      -->
      <el-form-item label="预约时间" prop="appointmentTime">
        <el-date-picker clearable v-model="dateRange" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择预约时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="服务类型" prop="serviceType">
        <el-select v-model="queryParams.serviceType" placeholder="请选择服务类型" clearable>
          <el-option v-for="dict in dict.type.bus_service_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.bus_appointment_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['business:appointment:add']">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="appointmentList" @selection-change="handleSelectionChange">
      <el-table-column label="客户名称" align="center" prop="customerName" />
      <el-table-column label="联系方式" align="center" prop="customerPhone" />
      <el-table-column label="预约时间" align="center" prop="appointmentTime" width="180">
        <template slot-scope="scope">
          <!-- 把字符串的时间解析为datetime类型展示到页面中 -->
          <span>{{ parseTime(scope.row.appointmentTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="到店时间" align="center" prop="actualArrivalTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.actualArrivalTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="车牌号码" align="center" prop="licensePlate" />
      <el-table-column label="汽车类型" align="center" prop="carSeries" />
      <el-table-column label="服务类型" align="center" prop="serviceType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bus_service_type" :value="scope.row.serviceType" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="info" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bus_appointment_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" :disabled="isEditOrCancel(scope.row)" icon="el-icon-edit"
            @click="handleUpdate(scope.row)" v-hasPermi="['business:appointment:edit']">编辑</el-button>
          <el-button size="mini" type="text" :disabled="isArrive(scope.row)" icon="el-icon-check"
            @click="handleArrive(scope.row)" v-hasPermi="['business:appointment:arrive']">到店</el-button>
          <el-button size="mini" type="text" icon="el-icon-shopping-cart-2" @click="handleSettle(scope.row)"
            v-hasPermi="['business:appointment:settle']" :disabled="getStatus(scope.row)" >结算</el-button>
          <el-button size="mini" type="text" :disabled="isEditOrCancel(scope.row)" icon="el-icon-close"
            @click="handleCancel(scope.row)" v-hasPermi="['business:appointment:cancel']">取消</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改养修信息预约对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="form.customerName" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="联系方式" prop="customerPhone">
          <el-input v-model="form.customerPhone" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="预约时间" prop="appointmentTime">
          <el-date-picker clearable v-model="form.appointmentTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择预约时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="车牌号码" prop="licensePlate">
          <el-input v-model="form.licensePlate" placeholder="请输入车牌号码" />
        </el-form-item>
        <el-form-item label="汽车类型" prop="carSeries">
          <el-input v-model="form.carSeries" placeholder="请输入汽车类型" />
        </el-form-item>
        <el-form-item label="服务类型" prop="serviceType">
          <el-select v-model="form.serviceType" placeholder="请选择服务类型">
            <el-option v-for="dict in dict.type.bus_service_type" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="info">
          <el-input v-model="form.info" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { arriveAppointment, listAppointment, getAppointment, cancelAppointment, addAppointment, updateAppointment } from "@/api/business/appointment";
import { getStatementByAppointmentId, addStatement } from "@/api/business/statement";
import { APPOINTMENT_STATUS_PENDING, APPOINTMENT_STATUS_ARRIVED, APPOINTMENT_STATUS_USER_CANCELED, APPOINTMENT_STATUS_TIMEOUT_CANCELED, APPOINTMENT_STATUS_SETTLED, APPOINTMENT_STATUS_PAYED } from "@/store/modules/business";

export default {
  name: "Appointment",
  dicts: ['bus_appointment_status', 'bus_service_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 养修信息预约表格数据
      appointmentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerName: null,
        customerPhone: null,
        appointmentTime: null,
        actualArrivalTime: null,
        licensePlate: null,
        carSeries: null,
        serviceType: null,
        info: null,
        status: null
      },
      // 表单参数
      form: {},
      // 日期范围
      dateRange: [],
      // 表单校验
      rules: {
        customerName: [
          { required: true, message: "客户名称不能为空", trigger: "blur" },
        ],
        customerPhone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        appointmentTime: [
          { required: true, message: "预约时间不能为空", trigger: "blur" },
        ],
        licensePlate: [
          {
            pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/,
            message: "请输入正确的车牌号码",
            trigger: "blur"
          }
        ],
        carSeries: [
          { required: true, message: "汽车类型不能为空", trigger: "blur" },
        ],
        serviceType: [
          { required: true, message: "服务类型不能为空", trigger: "blur" },
        ]

      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询养修信息预约列表 */
    getList() {
      this.loading = true;
      console.log(this.dateRange);
      console.log(this.queryParams);
      // 这段代码的意思是把日期参数和过滤查询的参数封装在一起，然后带过去后端。
      // 在原本参数基础上加上时间范围参数
      // 预约时间：params[beginTime]: 2023-04-13 00:00:00  params[endTime]: 2023-05-15 00:00:00
      console.log(this.addDateRange(this.queryParams, this.dateRange));
      listAppointment(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        console.log(response);
        this.appointmentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        customerName: null,
        customerPhone: null,
        appointmentTime: null,
        actualArrivalTime: null,
        licensePlate: null,
        carSeries: null,
        serviceType: null,
        createTime: null,
        info: null,
        status: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加养修信息预约";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAppointment(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改养修信息预约";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {  // 验证通过
          if (this.form.id != null) {
            updateAppointment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAppointment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 取消按钮操作 */
    handleCancel(row) {
      this.$modal.confirm('是否确认取消预约单编号为"' + row.id + '"的数据项？').then(function () {
        return cancelAppointment(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("取消成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/appointment/export', {
        ...this.queryParams
      }, `appointment_${new Date().getTime()}.xlsx`)
    },
    isEditOrCancel(row) {
      var status = row.status;
      if (status == APPOINTMENT_STATUS_PENDING || status == APPOINTMENT_STATUS_ARRIVED) {
        return false;
      }
      return true;
    },

    isArrive(row) {
      var status = row.status;
      if (status == APPOINTMENT_STATUS_PENDING) {
        return false;
      }
      return true;
    },
    /** 到店按钮操作 */
    handleArrive(row) {
      this.$modal.confirm('是否确认到店预约单编号为"' + row.id + '"的数据项？').then(function () {
        return arriveAppointment(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("到店成功");
      }).catch(() => { });
    },
    getStatus(row){
      var status = row.status;
      if (status == APPOINTMENT_STATUS_SETTLED || row.status == APPOINTMENT_STATUS_PAYED 
      || row.status == APPOINTMENT_STATUS_ARRIVED) {
        return false;
      }
      return true;
    },
    handleSettle(row) {
      // 有的预约单生成过结算单，先请求获取到结算单id，再访问对应结算单明细页面
      // 有的预约单没生成过结算单，弹出框，让用户确定，请求获取到结算单id，再访问对应结算单明细页面

      // 已结算或者已支付已到店 才可以结算
      if (row.status == APPOINTMENT_STATUS_SETTLED || row.status == APPOINTMENT_STATUS_PAYED) {
        getStatementByAppointmentId(row.id).then((res) => {   // 预约单id
          // 获取结算单id，要去跳转
          // 有结算单id
          if (res.data.id) {
            this.$router.push({
              path: '/business/statementItem',
              query: { statementId: res.data.id }
            });
          } else {
            // 没有结算单id
            this.$modal.msgError("没有对应的结算单");
          }
        }).catch(() => { });
      } else {  
        // 弹出框
        this.$modal.confirm('是否要生成结算单').then(function () {
          return addStatement({ appointmentId: row.id });  // 预约单id
        }).then((res) => {
          // 获取结算单id，要去跳转
          if (res.data.id) {
            this.$router.push({
              path: '/business/statementItem',
              query: { statementId: res.data.id }
            });
          } else {
            this.$modal.msgError("没有对应的结算单");
          }
        }).catch(() => { });
      }
    }
  }
};
</script>
